#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/wait.h>
int main(){
    int fds[2] = {0};
    if (pipe(fds) < 0){
        perror("pipe error");
        exit(1);
    }
    pid_t id = fork();
    if (id > 0){
        //父进程读
        ::close(fds[1]); //关闭写端
        dup2(fds[0],0);
        char buffer[1024];
        while(1){
            int n = ::read(0,buffer,sizeof(buffer));
            buffer[n] = 0;
            if (n > 0){
                cout << "我是父进程: " << getpid() << " 子进程说: " << buffer << endl; 
            }
            else if(n == 0){
                cout << "读端退出" << endl;
                break;
            }
            else {
                //读取失败
                cout << "读取失败" << endl;
                break;
            }
        }
        ::close(fds[0]); //关闭读端
        cout << "读端退出" << endl;
        //等待子进程退出
        int status = 0;
        int ret = waitpid(id,&status,0);
        if (ret > 0){
            std::cout << "子进程: " << id << "退出, errorcode: " << (status&0x7F) << endl; 
        } 
    }
    else if (id == 0){
        //子进程写
        ::close(fds[0]); //关闭读端
        string message = "hello world";
        while(1){
            int ret = ::write(fds[1],message.c_str(),message.size());
            cout << "ret: " << ret << endl;
            if (ret < 0){
                cout << "读端已经退出" << endl;
                break;
            }
            sleep(1);
            // break;
        }   
        ::close(fds[1]);
    }
    else {
        //创建失败
        perror("创建进程失败");
        exit(1);
    }
    return 0;
}